<?php
declare (strict_types=1);

namespace app\common\tool\Queue\Driver;

use app\common\tool\Queue\Exception\QueueException;
use think\Container;
use think\facade\Queue as ThinkQueue;

trait QueueTrait
{
    protected array $options = [
        'retry_num' => 1,
        'action' => 'handle',
        'data' => [],
    ];

    public function setData(array $data)
    {
        $this->options['data'] = $data;
        return $this;
    }

    public function setRetryNums(int $retryNums)
    {
        $this->options['retry_num'] = $retryNums;
        return $this;
    }

    public function setAction(string $action)
    {
        $this->options['action'] = $action;
        return $this;
    }

    /**
     * 分发消息队列
     * @param string $queueName - 别名
     * @param int $delay - 延迟执行时间
     * @return mixed
     * @throws QueueException
     */
    public function dispatch(string $queueName = null, int $delay = 0)
    {
        $res = $delay
            ? ThinkQueue::later($delay, static::class, $this->options, $queueName)
            : ThinkQueue::push(static::class, $this->options, $queueName);

        if (!$res) {
            throw new QueueException('发送队列失败');
        }
        return $res;
    }

    /**
     * @param array $vars
     * @param bool $newInstance
     * @return QueueTrait|object
     */
    public static function make(array $vars = [], bool $newInstance = false)
    {
        return Container::getInstance()->make(static::class, $vars, $newInstance);
    }
}